#include "StdAfx.h"
#include ".\ircreceiver.h"

CIRCReceiver::CIRCReceiver()
{
	sock=INVALID_SOCKET;
	m_parent=NULL;
	WSADATA w; //Winsock startup info
	WSAStartup (0x0202, &w);   // Fill in WSA info
	this->m_voluntaryDisconn=false;
}

LRESULT CIRCReceiver::OnSocketMessage(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
	switch (lParam)
	{
	case FD_CONNECT: //Connected OK
		MyTrace("FD_CONNECT\n");
		break;

	case FD_CLOSE: //Lost connection
/*		if(!m_voluntaryDisconn){
			SendMessage(m_hwndStatus, SB_SETTEXT, 0, (LPARAM)_T("Connection to mytaglist.com Lost, Reconnecting..."));
			Disconnect(false);
			this->ReConnect();
		}else{
*/
		Disconnect(false);
		SendMessage(m_hwndStatus, SB_SETTEXT, 0, (LPARAM)_T("Connection to mytaglist.com Lost."));                

		break;

	case FD_READ: //Incoming data to receive
		CString str;

		char* buf = str.GetBuffer(512);
		int len = recv(sock, buf, 511, 0);
		if(len== SOCKET_ERROR)
		{	
			Disconnect(false);		
			SendMessage(m_hwndStatus, SB_SETTEXT, 0, (LPARAM)_T("Connection to mytaglist.com Lost."));                
			break;
		}
		buf[len]=0;
		str.ReleaseBuffer();
		
		CString line;
		int line_start=0, line_end=0;
		while(line_start<len){
			line_end = str.Find('\n', line_start);
			if(line_end == -1)line_end=str.GetLength();
			line=str.Mid(line_start, line_end-line_start);
			
			MyTrace(line);

			line_start=line_end+1;
			
			if(line.Find("PING")==0){
				CString msg;
				msg.Format("PONG %s\r\n", line.Mid(4));
				send(sock, msg, msg.GetLength(),0);

				::PostMessage(m_hwndStatus, SB_SETTEXT, (255 ), (LPARAM)_T("Connected to mytaglist.com"));	
			}
			
			//:ni1!~ni1@ip98-164-215-249.oc.oc.cox.net PRIVMSG ni2 :cmd_id tag_id cmd   (from ni1 to ni2)
			int chat_start = line.Find("PRIVMSG");
			if(chat_start!=-1){
				CString chat_msg = line.Mid(chat_start+8);
				
				int tag_id=-1, tag_cmd=-1;
				int cmd_option;
				int numRead=_snscanf(chat_msg.Mid(chat_msg.Find(':')+1), chat_msg.GetLength(), "%d_%d %d", &tag_id, &tag_cmd, &cmd_option);
				
				if(numRead==3){
					DWORD cmd_id = MAKEWPARAM(tag_id, tag_cmd);
					CString talker = line.Mid(1, line.Find('!')-1);

					m_cmd_id_to_talker.insert(std::map<DWORD, CString>::value_type(cmd_id, talker));
					
					MyTrace(_T("Added talker %s for %d (id=%d, cmd=%d) \n"), talker.GetString(), cmd_id, tag_id, tag_cmd);
					
					if(cmd_id != CMD_LISTEN_FOR_ONE_EVENT)
						::PostMessage(m_parent, WM_IRC_CMD, cmd_id, cmd_option);
				}
			}
		}
		break;
	}
	return 0;
}